package com.deltabot.master.masterservers;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Jordi
 * Date: 1/06/13
 * Time: 09:19
 * To change this template use File | Settings | File Templates.
 */
public class MasterServerQueryT3 extends Thread{

    public String IP = "";
    public int port = 0;

    public int protocol = 1;

    public void run(){


        byte[] PACKER_HEADER = new byte[] { (byte) 0xFF, (byte) 0xFF,
                (byte) 0xFF, (byte) 0xFF };

        try {
            InetAddress serveraddress = InetAddress.getByName(IP);

            DatagramSocket socket = new DatagramSocket();
            socket.setSoTimeout(200);
            socket.connect(serveraddress, port);
            byte[] fin = new byte[300];
            byte[] data = ("getservers "+ protocol).getBytes();
            protocol += 1;
            System.arraycopy(PACKER_HEADER, 0, fin, 0, PACKER_HEADER.length);
            System.arraycopy(data, 0, fin, PACKER_HEADER.length, data.length);
            DatagramPacket output = new DatagramPacket(fin, fin.length,
                    serveraddress, port);
            socket.send(output);
            byte[] buffer = new byte[65565];
            DatagramPacket dp = new DatagramPacket(buffer, buffer.length);

            String DATA = "";

            try{
                while (true){
                    socket.receive(dp);
                    int length = dp.getLength();
                    if (dp.getData()[0] == (byte) 0xFF && dp.getData()[1] == (byte) 0xFF && dp.getData()[2] == (byte) 0xFF && dp.getData()[3] == (byte) 0xFF){
                        DATA = DATA + new String(dp.getData(),0, dp.getLength()).replace("����getserversResponse","");
                    }

                    String s = new String(dp.getData(),0, dp.getLength());

                }
            } catch(Exception e){
                System.out.println(e);
            }

            socket.close();
            System.out.println(DATA);
            byte[] receivedData = DATA.getBytes();

            List<String> serverList = new ArrayList<String>();
            int index = 22;
            int OFFSET = 7;
            byte[] byteAddress = new byte[OFFSET];
            while (index + OFFSET < receivedData.length) {
                System.arraycopy(receivedData, index + 1, byteAddress, 0, OFFSET);
                serverList.add(getAddressFromBytes(byteAddress));
                index += OFFSET;
            }

            int i =0;
            for(String server : serverList){
                i += 1;
            }

            if(i == 0){
                System.out.println((protocol - 1) + " is incorrect");
            } else {
                System.out.println((protocol - 1) + " is correct!!! Got " + i + " servers");
            }

            queryIW4servers.initQuery(serverList);

            //System.out.println("Finished contacting all T3 servers, will restart soon.");

           sleep(200);
           run();

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }

    private String getAddressFromBytes(final byte[] bytes) {
        String address = null;
        final int A = bytes[0] & 0xff;
        final int B = bytes[1] & 0xff;
        final int C = bytes[2] & 0xff;
        final int D = bytes[3] & 0xff;
        int port = bytes[4] & 0xff;
        port <<= 8;
        port |= bytes[5] & 0xff;
        address = A + "." + B + "." + C + "." + D + ":" + port;
        return address;
    }



}
